package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * admin用户登录
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {

        //参数校验
        if (adUserDto == null || StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名和密码不能为空");

        //查询用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);

        //密码加盐,加密
        String password = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
        if (!password.equals(adUser.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        //成功返回用户及token
        Map<String,Object> map = new HashMap<>();
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        map.put("token", AppJwtUtil.getToken(Long.valueOf(adUser.getId())));

        return ResponseResult.okResult(map);
    }
}
